package com.design.composite.web.action;

import com.design.composite.bean.ResponseResult;
import com.design.composite.entity.Material;
import com.design.composite.repository.DictRepository;
import com.design.composite.repository.MaterialRepository;
import com.design.composite.service.IMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author liuyajun
 * @desc 素材控制层
 */
@RestController
@RequestMapping(value = "/material")
public class MaterialController {

    @Autowired
    private IMaterialService materialService;

    @Autowired
    private MaterialRepository materialRepository;
    @Autowired
    private DictRepository dictRepository;

    /**
     * 获取分类列表
     *
     * @return
     */
    @RequestMapping("/list")
    public ResponseResult findList(Integer classifyId) {
        try {
            List<Material> list = materialService.findList(classifyId);
            return ResponseResult.success(list);
        } catch (Exception e) {
            return ResponseResult.fail("获取分类列表异常:" + e.getMessage());
        }
    }

    /**
     * 新增/更新分类 (id空为新增，反之更新)
     *
     * @param material
     * @return
     */
    @RequestMapping("/createOrUpdate")
    public ResponseResult add(@RequestBody Material material) {
        try {
            return materialService.add(material);
        } catch (Exception e) {
            return ResponseResult.fail("新增分类异常:" + e.getMessage());
        }
    }

    /**
     * 根据id删除分类
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable(name = "id") Integer id) {
        try {
            return materialService.delete(id);
        } catch (Exception e) {
            return ResponseResult.fail("删除素材异常:" + e.getMessage());
        }
    }

    /**
     * 根据id查询详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/get/{id}")
    public ResponseResult get(@PathVariable(name = "id") Integer id) {
        try {
            return ResponseResult.success(materialRepository.getOne(id));
        } catch (Exception e) {
            return ResponseResult.fail("查询素材详情异常:" + e.getMessage());
        }
    }


    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public ResponseResult uploadFile(@RequestParam(name = "file", required = true) MultipartFile file) {
        if (file == null) {
            return ResponseResult.fail("请选择文件");
        }
        return materialService.uploadFile(file);

    }

    /**
     * 获取素材图片存储路径（前端使用）
     */
    @RequestMapping("/preUrl")
    public String preUrl() {
        return dictRepository.findByCode("MATERIAL").getPath();
    }

}
